package jxta.test;

import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.peergroup.PeerGroup;
import net.jxta.protocol.PipeAdvertisement;

public class AdvListener extends Thread implements DiscoveryListener{

	private DiscoveryService discovery;
	private PeerGroup group;
	
	public AdvListener(DiscoveryService discovery, PeerGroup peer){
		
		this.discovery = discovery;
		this.group = group;
		
	}
	
	// FIXME marked due to ant errors
	
	//@Override
	public void discoveryEvent(DiscoveryEvent arg0) {
		System.out.println("Got response");		
	}

	@Override
	public void run() {
		long waittime = 10 * 1000L;
		
		discovery.addDiscoveryListener(this);

        try {
            // Add ourselves as a DiscoveryListener for DiscoveryResponse events
            //discovery.addDiscoveryListener(this);
            discovery.getRemoteAdvertisements(// no specific peer (propagate)
                    null, // Adv type
                    DiscoveryService.ADV, // Attribute = any
                    null, // Value = any
                    null, // one advertisement response is all we are looking for
                    1, // no query specific listener. we are using a global listener
                    this);
            while (true) {
                // wait a bit before sending a discovery message
                try {
                    System.out.println("Sleeping for :" + waittime);
                    Thread.sleep(waittime);
                } catch (Exception e) {
                    // ignored
                }
                System.out.println("Sending a Discovery Message");
                // look for any peer
                //for (Advertisment adv : discovery.getLocalAdvertisements(DiscoveryService.ADV, null, null)){
       /*         Enumeration<Advertisement> advs = discovery.getLocalAdvertisements(DiscoveryService.ADV, null, null);
                while (advs.hasMoreElements()){
                	System.out.println(advs.nextElement());
                	
                }*/
                discovery.getRemoteAdvertisements(
                        // no specific peer (propagate)
                        null,
                        // Adv type
                        DiscoveryService.ADV,
                        // Attribute = name
                        "Name",
                        // Value = the tutorial
                        //"Discovery tutorial",
                        "Test",
                        // one advertisement response is all we are looking for
                        1,
                        // no query specific listener. we are using a global listener
                        this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
		
	}

}
